
<template>
  <div class="documents-container">
    <div class="page-header">
      <div class="header-title">
        <h2>单据管理</h2>
        <span class="subtitle">管理所有运输相关单据和文档</span>
      </div>
      <div class="header-actions">
        <el-button-group>
          <el-button type="primary" @click="createDocument">
            <el-icon><DocumentAdd /></el-icon>新建单据
          </el-button>
          <el-button @click="batchExport">
            <el-icon><Download /></el-icon>批量导出
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="单据类型">
          <el-select v-model="searchForm.type" placeholder="选择类型" clearable>
            <el-option label="运输单" value="transport" />
            <el-option label="收据" value="receipt" />
            <el-option label="合同" value="contract" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已驳回" value="rejected" />
            <el-option label="已作废" value="voided" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="单据号/客户名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 单据列表 -->
    <el-table
      :data="documents"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="单据编号" width="150" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getDocumentTypeTag(row.type)">
            {{ getDocumentTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" show-overflow-tooltip />
      <el-table-column prop="customer" label="客户" width="150" />
      <el-table-column prop="amount" label="金额" width="120">
        <template #default="{ row }">
          ¥{{ row.amount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button 
              type="primary" 
              link
              @click="viewDocument(row)"
            >
              查看
            </el-button>
            <el-button 
              type="success" 
              link
              :disabled="row.status !== 'pending'"
              @click="approveDocument(row)"
            >
              审核
            </el-button>
            <el-button 
              type="danger" 
              link
              :disabled="row.status === 'voided'"
              @click="voidDocument(row)"
            >
              作废
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新建单据对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="新建单据"
      width="600px"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-position="top"
      >
        <el-form-item label="单据类型" prop="type">
          <el-select v-model="createForm.type" placeholder="选择单据类型" class="w-full">
            <el-option label="运输单" value="transport" />
            <el-option label="收据" value="receipt" />
            <el-option label="合同" value="contract" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="createForm.title" placeholder="请输入单据标题" />
        </el-form-item>

        <el-form-item label="客户" prop="customer">
          <el-select
            v-model="createForm.customer"
            placeholder="选择客户"
            filterable
            class="w-full"
          >
            <el-option
              v-for="customer in customers"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="createForm.amount"
            :precision="2"
            :step="100"
            :min="0"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="createForm.remarks"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  DocumentAdd,
  Download,
  Search
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  dateRange: [],
  keyword: ''
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(100)

// 表格数据
const documents = ref([
  {
    id: 'DOC20250314001',
    type: 'transport',
    title: '上海-北京运输单',
    customer: '上海ABC物流有限公司',
    amount: 5678.90,
    createTime: '2025-03-14 10:30:00',
    status: 'pending'
  },
  {
    id: 'DOC20250314002',
    type: 'receipt',
    title: '2月份运输费用收据',
    customer: '江苏XYZ贸易有限公司',
    amount: 12345.67,
    createTime: '2025-03-14 11:15:00',
    status: 'approved'
  }
])

// 选中的行
const selectedRows = ref([])

// 新建单据对话框
const createDialogVisible = ref(false)
const createFormRef = ref(null)
const createForm = reactive({
  type: '',
  title: '',
  customer: '',
  amount: 0,
  remarks: ''
})

// 表单验证规则
const createRules = {
  type: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入单据标题', trigger: 'blur' }],
  customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
}

// 客户列表
const customers = ref([
  { id: 1, name: '上海ABC物流有限公司' },
  { id: 2, name: '江苏XYZ贸易有限公司' },
  { id: 3, name: '广州123快运有限公司' }
])

// 获取单据类型标签
const getDocumentTypeTag = (type) => {
  const typeMap = {
    'transport': 'primary',
    'receipt': 'success',
    'contract': 'warning',
    'other': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取单据类型文本
const getDocumentTypeText = (type) => {
  const textMap = {
    'transport': '运输单',
    'receipt': '收据',
    'contract': '合同',
    'other': '其他'
  }
  return textMap[type] || '其他'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'voided': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待审核',
    'approved': '已审核',
    'rejected': '已驳回',
    'voided': '已作废'
  }
  return textMap[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  ElMessage.success('执行搜索')
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  ElMessage.success('已重置搜索条件')
}

// 处理选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  // 重新加载数据
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  // 重新加载数据
}

// 新建单据
const createDocument = () => {
  createDialogVisible.value = true
}

// 提交新建
const submitCreate = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    // 提交表单数据
    ElMessage.success('单据创建成功')
    createDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 批量导出
const batchExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的单据')
    return
  }
  ElMessage.success(`已选择${selectedRows.value.length}个单据进行导出`)
}

// 查看单据
const viewDocument = (document) => {
  ElMessage.info(`查看单据：${document.id}`)
}

// 审核单据
const approveDocument = (document) => {
  ElMessageBox.confirm(
    '确认审核通过该单据？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    document.status = 'approved'
    ElMessage.success('单据已审核通过')
  }).catch(() => {})
}

// 作废单据
const voidDocument = (document) => {
  ElMessageBox.confirm(
    '确认作废该单据？作废后不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    document.status = 'voided'
    ElMessage.success('单据已作废')
  }).catch(() => {})
}

// 处理文件变化
const handleFileChange = (file) => {
  console.log('选择文件:', file)
}
</script>

<style scoped>
.documents-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.search-bar {
  background-color: var(--el-bg-color-page);
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.w-full {
  width: 100%;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
}

:deep(.el-upload__tip) {
  color: var(--el-text-color-secondary);
}
</style>